package com.ziiwee.reduce.describe.creators.handlers;

import com.ziiwee.reduce.describe.FieldDescribe;
import com.ziiwee.reduce.describe.HttpRequestParameterType;
import org.springframework.core.ResolvableType;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;

import java.lang.reflect.AnnotatedElement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author ziiwee
 * @data 2020/8/12
 */
public class ControllerHandlerDescribeCreator extends AbstractHandlerDescribeCreator{

    private final RequestMappingInfo requestMapping;
    private final HandlerMethod handlerMethod;

    public ControllerHandlerDescribeCreator(RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod) {
        this.requestMapping = requestMappingInfo;
        this.handlerMethod = handlerMethod;
    }

    @Override
    public AnnotatedElement getElement() {
        return handlerMethod.getMethod();
    }

    @Override
    public ResolvableType getDefaultType() {
        return ResolvableType.forMethodReturnType(handlerMethod.getMethod());
    }

    @Override
    public List<String> getMethods() {
        return requestMapping.getMethodsCondition().getMethods().stream().map(Enum::name).collect(Collectors.toList());
    }

    @Override
    public List<String> getPatterns() {
        return new ArrayList<>(requestMapping.getPatternsCondition().getPatterns());
    }

    @Override
    public Map<HttpRequestParameterType, List<FieldDescribe>> getParameters() {
        return getParameters(handlerMethod.getMethod());
    }

    @Override
    public String getName() {
        return handlerMethod.getMethod().getName();
    }
}
